package com.ruoyi.statistics.controller;

import java.util.List;
import java.util.Map;
import java.util.HashMap;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.statistics.service.IOrderAnalyseService;
import com.ruoyi.statistics.service.impl.OrderAnalyseServiceImpl;

/**
 * 订单数据分析Controller
 * 
 * @author ruoyi
 * @date 2025-01-18
 */
@Anonymous
@RestController
@RequestMapping("/statistics/order")
public class OrderAnalyseController extends BaseController
{
    private static final Logger logger = LoggerFactory.getLogger(OrderAnalyseController.class);
    
    @Autowired
    private IOrderAnalyseService orderAnalyseService;

    /**
     * 获取订单核心指标数据
     */
    @GetMapping("/core-metrics")
    public AjaxResult getOrderCoreMetrics(
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate)
    {
        Long orgId = getOrgId();
        Map<String, Object> data = orderAnalyseService.getOrderMetrics(orgId, startDate, endDate);
        return AjaxResult.success(data);
    }

    /**
     * 获取订单核心指标数据（别名）
     */
    @GetMapping("/metrics")
    public AjaxResult getOrderMetrics(
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate)
    {
        return getOrderCoreMetrics(startDate, endDate);
    }

    /**
     * 获取订单详情列表
     */
    @GetMapping("/details")
    public AjaxResult getOrderDetails(
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String userName,
            @RequestParam(required = false) String orderStartTime,
            @RequestParam(required = false) String orderEndTime,
            @RequestParam(required = false) String minTotalAmount,
            @RequestParam(required = false) String maxTotalAmount,
            @RequestParam(required = false) String minPaymentAmount,
            @RequestParam(required = false) String maxPaymentAmount,
            @RequestParam(required = false) String paymentStatus)
    {
        try {
            Long orgId = getOrgId();
            
            // 构造筛选条件
            Map<String, Object> filterParams = new HashMap<>();
            if (userName != null && !userName.trim().isEmpty()) {
                filterParams.put("userName", userName.trim());
            }
            if (orderStartTime != null && !orderStartTime.trim().isEmpty()) {
                filterParams.put("orderStartTime", orderStartTime.trim());
            }
            if (orderEndTime != null && !orderEndTime.trim().isEmpty()) {
                filterParams.put("orderEndTime", orderEndTime.trim());
            }
            if (minTotalAmount != null && !minTotalAmount.trim().isEmpty()) {
                filterParams.put("minTotalAmount", minTotalAmount.trim());
            }
            if (maxTotalAmount != null && !maxTotalAmount.trim().isEmpty()) {
                filterParams.put("maxTotalAmount", maxTotalAmount.trim());
            }
            if (minPaymentAmount != null && !minPaymentAmount.trim().isEmpty()) {
                filterParams.put("minPaymentAmount", minPaymentAmount.trim());
            }
            if (maxPaymentAmount != null && !maxPaymentAmount.trim().isEmpty()) {
                filterParams.put("maxPaymentAmount", maxPaymentAmount.trim());
            }
            if (paymentStatus != null && !paymentStatus.trim().isEmpty()) {
                filterParams.put("paymentStatus", paymentStatus.trim());
            }
            
            // 调用带筛选条件的订单详情方法
            Map<String, Object> data = ((OrderAnalyseServiceImpl) orderAnalyseService).getOrderDetailsWithParams(orgId, startDate, endDate, pageNum, pageSize, filterParams);
            
            // 确保返回正确的分页格式
            AjaxResult result = AjaxResult.success(data);
            result.put("rows", data.get("rows"));
            result.put("total", data.get("total"));
            
            return result;
        } catch (Exception e) {
            logger.error("获取订单详情列表失败", e);
            return AjaxResult.error("获取订单详情失败: " + e.getMessage());
        }
    }

    /**
     * 获取订单转化漏斗数据
     */
    @GetMapping("/funnel")
    public AjaxResult getOrderFunnel(
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate)
    {
        Long orgId = getOrgId();
        List<Map<String, Object>> data = orderAnalyseService.getOrderFunnel(orgId, startDate, endDate);
        return AjaxResult.success(data);
    }

    /**
     * 获取订单趋势数据
     */
    @GetMapping("/trend")
    public AjaxResult getOrderTrend(
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate,
            @RequestParam(defaultValue = "day") String timeType)
    {
        Long orgId = getOrgId();
        List<Map<String, Object>> data = orderAnalyseService.getOrderTrend(orgId, startDate, endDate, timeType);
        return AjaxResult.success(data);
    }

    /**
     * 获取订单金额分布数据
     */
    @GetMapping("/amount-distribution")
    public AjaxResult getOrderAmountDistribution(
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate)
    {
        try {
            Long orgId = getOrgId();
            List<Map<String, Object>> data = ((OrderAnalyseServiceImpl) orderAnalyseService).getOrderAmountDistribution(orgId, startDate, endDate);
            return AjaxResult.success(data);
        } catch (Exception e) {
            logger.error("获取订单金额分布数据失败", e);
            return AjaxResult.error("获取订单金额分布数据失败: " + e.getMessage());
        }
    }

    /**
     * 导出订单分析数据
     */
    @Log(title = "订单分析", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public void export(HttpServletResponse response,
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate,
            @RequestParam(required = false) String userName,
            @RequestParam(required = false) String orderStartTime,
            @RequestParam(required = false) String orderEndTime,
            @RequestParam(required = false) String minTotalAmount,
            @RequestParam(required = false) String maxTotalAmount,
            @RequestParam(required = false) String minPaymentAmount,
            @RequestParam(required = false) String maxPaymentAmount,
            @RequestParam(required = false) String paymentStatus)
    {
        try {
            Long orgId = getOrgId();
            
            // 构造筛选条件
            Map<String, Object> filterParams = new HashMap<>();
            if (userName != null && !userName.trim().isEmpty()) {
                filterParams.put("userName", userName.trim());
            }
            if (orderStartTime != null && !orderStartTime.trim().isEmpty()) {
                filterParams.put("orderStartTime", orderStartTime.trim());
            }
            if (orderEndTime != null && !orderEndTime.trim().isEmpty()) {
                filterParams.put("orderEndTime", orderEndTime.trim());
            }
            if (minTotalAmount != null && !minTotalAmount.trim().isEmpty()) {
                filterParams.put("minTotalAmount", minTotalAmount.trim());
            }
            if (maxTotalAmount != null && !maxTotalAmount.trim().isEmpty()) {
                filterParams.put("maxTotalAmount", maxTotalAmount.trim());
            }
            if (minPaymentAmount != null && !minPaymentAmount.trim().isEmpty()) {
                filterParams.put("minPaymentAmount", minPaymentAmount.trim());
            }
            if (maxPaymentAmount != null && !maxPaymentAmount.trim().isEmpty()) {
                filterParams.put("maxPaymentAmount", maxPaymentAmount.trim());
            }
            if (paymentStatus != null && !paymentStatus.trim().isEmpty()) {
                filterParams.put("paymentStatus", paymentStatus.trim());
            }
            
            // 调用带筛选条件的导出方法
            ((OrderAnalyseServiceImpl) orderAnalyseService).exportOrderDataWithParams(response, orgId, startDate, endDate, filterParams);
        } catch (Exception e) {
            logger.error("导出订单分析数据失败", e);
            throw new RuntimeException("导出订单分析数据失败: " + e.getMessage());
        }
    }

    /**
     * 导出订单核心数据
     */
    @Log(title = "订单分析", businessType = BusinessType.EXPORT)
    @GetMapping("/export/core")
    public void exportCore(HttpServletResponse response,
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate)
    {
        export(response, startDate, endDate, null, null, null, null, null, null, null, null);
    }

    /**
     * 导出订单漏斗数据
     */
    @Log(title = "订单分析", businessType = BusinessType.EXPORT)
    @GetMapping("/export/funnel")
    public void exportFunnel(HttpServletResponse response,
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate)
    {
        export(response, startDate, endDate, null, null, null, null, null, null, null, null);
    }
}